package com.hice.demo.springboot.jta.service.impl;

import org.apache.log4j.Logger;
import com.hice.demo.springboot.jta.dao.databases1.UserMapper;
import com.hice.demo.springboot.jta.dao.databases2.MessageMapper;
import com.hice.demo.springboot.jta.model.Message;
import com.hice.demo.springboot.jta.model.User;
import com.hice.demo.springboot.jta.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by hyson on 2017/3/10.
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    private static Logger logger = Logger.getLogger(UserServiceImpl.class);
    @Autowired
    UserMapper userMapper;
    @Autowired
    MessageMapper messageMapper;

    @Override
    public Integer add(User user) {
        //这里必须要抛出异常，不然JTA不会回滚数据
        try {
            userMapper.add(user);
            System.out.println(1 / 0);
            Message message = new Message();
            message.setName(user.getName());
            message.setContent(user.getAge().toString());
            messageMapper.add(message);
        } catch (Exception e) {
            logger.error("add异常");
            throw new RuntimeException();
        }
        return 1;
    }

    @Override
    public Integer del(Long id) {
        //这里必须要抛出异常，不然JTA不会回滚数据
        try {
            userMapper.del(id);
            messageMapper.del(id);
        } catch (Exception e) {
            logger.error("del异常");
            throw new RuntimeException();
        }
        return 1;
    }

}